<template>
    <t-space direction="vertical" size="large" class="tdesign-demo-form-status">

        <t-form ref="formValidatorStatus" :data="shop" :rules="rules" @reset="onReset" @submit="onSubmit"
            @validate="onValidate">
            <t-form-item label="商品名称" name="name">
                <t-input v-model="shop.name" placeholder="请输入商品名称"></t-input>
            </t-form-item>

            <t-form-item label="商品图片" name="imgUrl">
                <t-input v-model="shop.imgUrl" placeholder="请输入商品分类" hidden></t-input>
                <!-- <t-upload name="file" v-model="shop.imgUrl" method="post" action="/api/img/upload2" theme="image"
                    tips="请选择单张图片文件上传" draggable=true @fail="formatResponse" @success="imgSUC" :data="{ id:1 }"
                    @format-response="formatResponse"></t-upload> -->
                <t-upload ref="uploadRef2" v-model="file2"
                    action="https://service-bv448zsw-1257786608.gz.apigw.tencentcs.com/api/upload-demo" theme="image"
                    accept="image/*" :disabled="disabled" :auto-upload="autoUpload"
                    :upload-all-files-in-one-request="uploadAllFilesInOneRequest" :format-response="formatImgResponse"
                    @fail="handleFail"></t-upload>
            </t-form-item>
            <t-form-item label="商品价格" name="price">
                <t-input v-model="shop.price" placeholder="请输入商品价格"></t-input>
            </t-form-item>
            <t-form-item label="商品分类" name="fenlei">
                <t-input v-model="shop.fenlei" placeholder="请输入商品分类"></t-input>
            </t-form-item>
            <t-form-item label="商品标签" name="label">
                <t-check-tag shape="round" v-for="(tag, index) in label" :key="index" style="margin-left:7px;"
                    :default-checked="tag.defaultChecked" :checked="shop.label.some(n=>n.id==tag.id)"
                    :disabled="!!tag.disabled" @click="handleClick(tag, index)" @change="handleChange">
                    {{ tag.text }}
                </t-check-tag>
                <!-- <el-check-tag v-for="(tag, index) in label" :key="index" :checked="checked" @change="onChange">{{
                tag.text }}</el-check-tag>
                <t-input v-model="shop.label" hidden placeholder="请输入商品分类"></t-input> -->
            </t-form-item>
            <t-form-item :status-icon="false">
                <t-space size="small">
                    <t-button theme="primary" type="submit">修改</t-button>
                    <!-- <t-button theme="default" variant="base" type="reset">重置</t-button> -->
                </t-space>
            </t-form-item>
        </t-form>
    </t-space>
</template>
<script setup>
import { ref, onMounted, watch, computed, toRefs } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { addNewFood } from '@/http/modules/store';
import { getFoodlabelData, UpdataFoodListInfo } from '@/http/modules/store'
import mitt from '@/utils/mitt/index'

const file2 = ref([{ name: 'demo-image-1.png', url: 'https://tdesign.gtimg.com/demo/demo-image-1.png' }]);

const shop = ref({
    _id: new Date().getTime() + Math.floor(Math.random()) * 11,
    shopid: 1,
    name: '33',
    price: '',
    fenlei: "",
    imgUrl: "",
    label: []
})

const shopComputed = computed(() => {
    // const { label, _id, shopid, icon, name, price, fenlei } = toRefs();
    return {
        _id: shop.value._id,
        shopid: shop.value.shopid,
        icon: shop.value.icon,
        name: shop.value.name,
        price: shop.value.price,
        fenlei: shop.value.fenlei,
        label: shop.value.label.map(n => n.id)
    }
})

const props = defineProps({
    data: {
        default: () => { },
        type: Object
    }
})

watch(props, () => {
    shop.value = {
        ...JSON.parse(JSON.stringify(props.data)),
        imgUrl: props.data.icon
    }
    file2.value = [{
        name: 'demo-image-1.png',
        url: props.data.icon
    }]

})

const handleClick = (tag, index) => {
    // console.log(tag, index, '修改了', shop.value.label);
    if (shop.value.label.some(n => n.id == tag.id)) {
        const i = shop.value.label.findIndex(n => n.id == tag.id);
        shop.value.label.splice(i, 1);
    } else {
        shop.value.label.push(tag)
    }
};

const handleChange = (isChecked) => {
    console.log(isChecked);
};



const label = ref();
getFoodlabelData().then(res => {
    label.value = res
    console.log('label', res);
})




const priceCheck = (val) => {
    if (isNaN(Number(val))) {
        return { result: false, message: '请输入数字', type: 'error' };
    }
    return { result: true, message: '', type: 'success' };
};

const labelCheck = (val) => {
    if (val.length == 0) {
        return { result: false, message: '请加入至少一个标签', type: 'error' };
    }
    return { result: true, message: '', type: 'success' };
};

const rules = {
    name: [
        { required: true, message: '商品名称必填', type: 'error' },
        {
            min: 2,
            message: '商品名称至少需要两个字',
            type: 'error',
            trigger: 'blur',
        },
    ],
    price: [
        { required: true, message: '价格必填', type: 'error' },
        { validator: priceCheck }
    ],
    fenlei: [
        { required: true, message: '商品分类必填', type: 'error' },
    ],
    imgUrl: [
        { required: true, message: '必须上传图片', type: 'error' },
    ],
    label: [
        { validator: labelCheck }
    ]
};

const onSubmit = ({ validateResult, firstError, e }) => {
    e.preventDefault();
    if (validateResult === true) {
        UpdataFoodListInfo(shopComputed.value).then(res => {
            // console.log('上传商品成功！', res);
        })
        mitt.emit("updateFood")
        mitt.emit("closeChouTi2")
        MessagePlugin.success(`修改${shopComputed.value.name}成功`);
    } else {
        console.log('Validate Errors: ', firstError, validateResult);
        MessagePlugin.warning(firstError);
    }
};

const imgSUC = (c) => {
    shop.value.imgUrl = c.response.imageUrl
    console.log(shop.value);
}
const onReset = () => {
    shop.value = {
        _id: '',
        shopid: '',
        name: '',
        price: '',
        fenlei: "",
        imgUrl: "",
        label: []
    }
    MessagePlugin.success('重置成功');
};


</script>
<style>
.tdesign-demo-form-status .t-input {
    width: 520px;
}
</style>
  